package cn.yanji.service.impl;

import cn.yanji.service.ExecuteService;
import cn.yanji.service.HttpService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Objects;

/**
 * @author yanji w2c17lin@qq.com
 * @since 2018/11/7 上午 11:54
 */
@Service
public class HttpServiceImpl implements HttpService {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	private OkHttpClient okHttpClient;

	public HttpServiceImpl() {
		okHttpClient = new OkHttpClient();
	}

	@Override
	public String download(String url) {
		if (StringUtils.isEmpty(url)) return null;
		Request request = new Request.Builder().url(url).build();

		try {
			Response response = okHttpClient.newCall(request).execute();
			if (Objects.isNull(response.body())) return null;

			url = StringUtils.remove(url, "http://img.hzqatc.com/qaydt/img/exam/skill/");
			url = StringUtils.remove(url, "?ver=1.0.0.2");
			url = StringUtils.isEmpty(url) ? String.valueOf(System.nanoTime()) : url;

			byte[] bytes = response.body().bytes();
			logger.debug("下载图片成功，正在写入文件");

			File dir = new File(ExecuteService.GIF_PATH);
			if (!dir.exists()) {
				//noinspection ResultOfMethodCallIgnored
				dir.mkdirs();
			}

			OutputStream outputStream = new FileOutputStream(ExecuteService.GIF_PATH + url);
			outputStream.write(bytes);
			outputStream.flush();
			outputStream.close();
			response.close();
			logger.debug("下载图片完成：{}", ExecuteService.GIF_PATH + url);

			return url;
		} catch (IOException e) {
			logger.error("下载图片失败", e);
			return null;
		}
	}

}

